/**
 * MainFragmentActivity.java
 * com.ximalaya.ting.android.opensdk.test
 *
 *
 *   ver     date      		author
 * ──────────────────────────────────
 *   		 2015-5-25 		jack.qin
 *
 * Copyright (c) 2015, TNT All Rights Reserved.
 */

package com.ximalaya.ting.android.opensdk.test;

import java.io.File;

import net.tsz.afinal.FinalBitmap;
import net.tsz.afinal.FinalHttp;
import net.tsz.afinal.http.AjaxCallBack;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Environment;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.app.NotificationCompat;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.PagerTabStrip;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.RemoteViews;
import android.widget.SeekBar;
import android.widget.SeekBar.OnSeekBarChangeListener;
import android.widget.TextView;

import com.ximalaya.ting.android.opensdk.datatrasfer.CommonRequest;
import com.ximalaya.ting.android.opensdk.model.PlayableModel;
import com.ximalaya.ting.android.opensdk.model.advertis.Advertis;
import com.ximalaya.ting.android.opensdk.model.advertis.AdvertisList;
import com.ximalaya.ting.android.opensdk.model.live.radio.Radio;
import com.ximalaya.ting.android.opensdk.model.live.schedule.Schedule;
import com.ximalaya.ting.android.opensdk.model.track.Track;
import com.ximalaya.ting.android.opensdk.player.XmPlayerManager;
import com.ximalaya.ting.android.opensdk.player.service.IXmAdsStatusListener;
import com.ximalaya.ting.android.opensdk.player.service.IXmPlayerStatusListener;
import com.ximalaya.ting.android.opensdk.player.service.XmPlayerException;
import com.ximalaya.ting.android.opensdk.test.constants.Constants;
import com.ximalaya.ting.android.opensdk.test.fragment.RadiosFragment;
import com.ximalaya.ting.android.opensdk.test.fragment.ScheduleFragment;
import com.ximalaya.ting.android.opensdk.test.fragment.TracksFragment;
import com.ximalaya.ting.android.opensdk.test.util.ToolUtil;

/**
 * ClassName:MainFragmentActivity 
 * 
 * @author jack.qin
 * @version
 * @since Ver 1.1
 * @Date 2015-5-25 下午5:51:12
 * 
 * @see
 */
public class MainFragmentActivity extends FragmentActivity
{
	private static final String[] CONTENT = new String[] { "点播", "直播", "节目表"};
	private String mAppSecret = "f80078fb60cc513ec5a5082953bd748f";
	private static final String TAG = "MainFragmentActivity";

	private TextView mTextView;
	private ImageButton mBtnPreSound;
	private ImageButton mBtnPlay;
	private ImageButton mBtnNextSound;
	private ImageButton mBtnNextPage;
	private SeekBar mSeekBar;
	private ImageView mSoundCover;
	private ProgressBar mProgress;

	private ViewPager mViewPager;
	private PagerTabStrip mIndicator;
	private PagerAdapter mAdapter;
	
	private Context mContext;

	private FinalBitmap mFinalBitmap;
	private FinalHttp mFinalHttp;
	private XmPlayerManager mPlayerManager;
	private CommonRequest mXimalaya;

	private boolean mUpdateProgress = true;

	private NotificationManager mNotificationManager;
	private int mNotificationId = (int) System.currentTimeMillis();
	private Notification mNotification;
	private RemoteViews mRemoteView;

	private TracksFragment mTracksFragment;
	private RadiosFragment mRadiosFragment;
	private ScheduleFragment mScheduleFragment;
	private BaseFragment mCurrFragment;
	
	@Override
	protected void onCreate(Bundle arg0)
	{
		super.onCreate(arg0);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		
		setContentView(R.layout.act_main);

		mContext = MainFragmentActivity.this;
		
		mViewPager = (ViewPager) findViewById(R.id.pager);
		mIndicator = (PagerTabStrip) findViewById(R.id.indicator);
		mTextView = (TextView) findViewById(R.id.message);
		mBtnPreSound = (ImageButton) findViewById(R.id.pre_sound);
		mBtnPlay = (ImageButton) findViewById(R.id.play_or_pause);
		mBtnNextSound = (ImageButton) findViewById(R.id.next_sound);
		mBtnNextPage = (ImageButton) findViewById(R.id.next_page);
		mSeekBar = (SeekBar) findViewById(R.id.seek_bar);
		mSoundCover = (ImageView) findViewById(R.id.sound_cover);
		mProgress = (ProgressBar) findViewById(R.id.buffering_progress);
		
		mViewPager.setOffscreenPageLimit(2);
		mIndicator.setTabIndicatorColor(Color.RED);
		mIndicator.setTextColor(Color.RED);

		mAdapter = new SlidingPagerAdapter(getSupportFragmentManager());
		mViewPager.setAdapter(mAdapter);
		
		mNotificationManager = (NotificationManager) mContext
				.getSystemService(Context.NOTIFICATION_SERVICE);

		mFinalBitmap = FinalBitmap.create(mContext.getApplicationContext());
		mFinalBitmap.configLoadingImage(R.drawable.ic_launcher);
		mFinalBitmap.configLoadfailImage(R.drawable.ic_launcher);
		
		mFinalHttp = new FinalHttp();
		
		mXimalaya = CommonRequest.getInstanse();
		mXimalaya.init(mContext, mAppSecret);
		mPlayerManager = XmPlayerManager.getInstance(mContext);
		mNotification = createNotification();
		mPlayerManager.init(mNotificationId, mNotification);
		mPlayerManager.addPlayerStatusListener(mPlayerStatusListener);
		mPlayerManager.addAdsStatusListener(mAdsListener);
		
		mViewPager.setOnPageChangeListener(new OnPageChangeListener()
		{

			@Override
			public void onPageSelected(int arg0)
			{
				if (arg0 == 0)
				{
					mCurrFragment = mTracksFragment;
				}
				else if (arg0 == 1)
				{
					mCurrFragment = mRadiosFragment;
				}
				else if (arg0 == 2)
				{
					mCurrFragment = mScheduleFragment;
					if (mCurrFragment != null)
					{
						mCurrFragment.refresh();
					}
				}
				else
				{
					mCurrFragment = null;
				}
				if (mCurrFragment != null)
				{
//					mCurrFragment.refresh();
				}
			}

			@Override
			public void onPageScrolled(int arg0, float arg1, int arg2)
			{

			}

			@Override
			public void onPageScrollStateChanged(int arg0)
			{

			}
		});
		
		mSeekBar.setOnSeekBarChangeListener(new OnSeekBarChangeListener()
		{

			@Override
			public void onStopTrackingTouch(SeekBar seekBar)
			{
				mPlayerManager.seekToByPercent(seekBar.getProgress()
						/ (float) seekBar.getMax());
				mUpdateProgress = true;
			}

			@Override
			public void onStartTrackingTouch(SeekBar seekBar)
			{
				mUpdateProgress = false;
			}

			@Override
			public void onProgressChanged(SeekBar seekBar, int progress,
					boolean fromUser)
			{
			}
		});

		mBtnPreSound.setOnClickListener(new OnClickListener()
		{

			@Override
			public void onClick(View v)
			{
				mPlayerManager.playPre();
			}
		});

		mBtnPlay.setOnClickListener(new OnClickListener()
		{

			@Override
			public void onClick(View v)
			{
				if (mPlayerManager.isPlaying())
				{
					mPlayerManager.pause();
				}
				else
				{
					mPlayerManager.play();
				}
			}
		});

		mBtnNextSound.setOnClickListener(new OnClickListener()
		{

			@Override
			public void onClick(View v)
			{
				mPlayerManager.playNext();
			}
		});

		mBtnNextPage.setOnClickListener(new OnClickListener()
		{

			@Override
			public void onClick(View v)
			{
				if (mCurrFragment != null)
				{
					mCurrFragment.refresh();
				}
			}
		});
	}

	@Override
	public void onBackPressed()
	{
		Log.e(TAG, "onBackPressed");
		if (mPlayerManager != null)
		{
			mPlayerManager.stop();
			mPlayerManager.removePlayerStatusListener(mPlayerStatusListener);
			mPlayerManager.release();
		}
		super.onBackPressed();
	}
	
	private String generateFilePath(String baseDir, String url)
	{
		if (TextUtils.isEmpty(baseDir))
		{
			baseDir = Environment.getExternalStorageDirectory() + "/img_chache/";
		}
		File dir = new File(baseDir);
		if (dir.isFile())
		{
			dir.delete();
		}
		if (!dir.exists())
		{
			dir.mkdirs();
		}
		return baseDir + System.currentTimeMillis() + getSubfixByUrl(url);
	}
	
	private String getSubfixByUrl(String url)
	{
		if (TextUtils.isEmpty(url))
		{
			return "";
		}
		if (url.contains("."))
		{
			return url.substring(url.lastIndexOf("."));
		}
		return ".jpg";
	}
	
	private Notification createNotification()
	{
		NotificationCompat.Builder builder = new NotificationCompat.Builder(
				mContext);

		Intent main = new Intent(mContext, MainFragmentActivity.class);
		PendingIntent mainPi = PendingIntent.getActivity(mContext, 0, main, 0);
		
		Intent play = new Intent(Constants.ACTION_CONTROL_PLAY_PAUSE);
		PendingIntent playPi = PendingIntent.getBroadcast(mContext, 0, play, 0);
		
//		Intent pre = new Intent(Constants.ACTION_CONTROL_PLAY_PRE);
//		PendingIntent prePi = PendingIntent.getBroadcast(mContext, 0, pre, 0);
		
		Intent next = new Intent(Constants.ACTION_CONTROL_PLAY_NEXT);
		PendingIntent nextPi = PendingIntent.getBroadcast(mContext, 0, next, 0);
		
		mRemoteView = new RemoteViews(mContext.getPackageName(),
				R.layout.notify_show_playmusic);
		mRemoteView.setOnClickPendingIntent(R.id.img_notifyIcon, mainPi);
		mRemoteView.setOnClickPendingIntent(R.id.img_notifyPlayOrPause, playPi);
		mRemoteView.setOnClickPendingIntent(R.id.img_notifyNext, nextPi);
		
		builder.setContent(mRemoteView).setSmallIcon(R.drawable.ic_launcher)
				.setContentTitle("XMLY").setContentText("ximalaya")
				.setContentIntent(mainPi);
		return builder.build();
	}

	class SlidingPagerAdapter extends FragmentPagerAdapter
	{
		public SlidingPagerAdapter(FragmentManager fm)
		{
			super(fm);
		}

		@Override
		public Fragment getItem(int position)
		{
			Fragment f = null;
			if (0 == position)
			{
				if (mTracksFragment == null)
				{
					mTracksFragment = new TracksFragment();
				}
				f = mTracksFragment;
			}
			else if (1 == position)
			{
				if (mRadiosFragment == null)
				{
					mRadiosFragment = new RadiosFragment();
				}
				f = mRadiosFragment;
			}
			else if (2 == position)
			{
				if (mScheduleFragment == null)
				{
					mScheduleFragment = new ScheduleFragment();
				}
				f = mScheduleFragment;
			}
			return f;
		}

		@Override
		public CharSequence getPageTitle(int position)
		{
			return CONTENT[position % CONTENT.length];
		}

		@Override
		public int getCount()
		{
			return CONTENT.length;
		}
	}

	private IXmPlayerStatusListener mPlayerStatusListener = new IXmPlayerStatusListener()
	{

		@Override
		public void onSoundPrepared()
		{
			Log.e(TAG, "onSoundPrepared");
			mSeekBar.setEnabled(true);
			mProgress.setVisibility(View.GONE);
		}

		@Override
		public void onSoundSwitch(int currIndex, int lastIndex, int played)
		{
			Log.e(TAG, "onSoundSwitch index:" + currIndex);
			PlayableModel model = mPlayerManager.getCurrSound();
			if (model != null)
			{
				String title = null;
				String msg = null;
				String coverUrl = null;
				String coverSmall = null;
				if (model instanceof Track)
				{
					Track info = (Track) model;
					title = info.getTrackTitle();
					msg = info.getAnnouncer() == null ? "" : info.getAnnouncer().getNickname();
					coverUrl = info.getCoverUrlLarge();
					coverSmall = info.getCoverUrlMiddle();
				}
				else if (model instanceof Schedule)
				{
					Schedule program = (Schedule) model;
					msg = program.getRelatedProgram().getProgramName();
					title = program.getRelatedProgram().getProgramName();
					coverUrl = program.getRelatedProgram().getBackPicUrl();
					coverSmall = program.getRelatedProgram().getBackPicUrl();
				}
				else if (model instanceof Radio)
				{
					Radio radio = (Radio) model;
					title = radio.getRadioName();
					msg = radio.getRadioDesc();
					coverUrl = radio.getCoverUrlLarge();
					coverSmall = radio.getCoverUrlSmall();
				}
				mTextView.setText(title);
				mFinalBitmap.display(mSoundCover, coverUrl);
				if (!TextUtils.isEmpty(coverSmall))
				{
					updateRemoteViewIcon(coverSmall);
				}
				else
				{
					Log.e(TAG, "download img null");
				}
				updateNotification(title, msg, true, true);
			}
			updateButtonStatus();
		}

		private void updateNotification(String title, String msg, boolean isPlaying,
				boolean hasNext)
		{
			if (!TextUtils.isEmpty(title))
			{
				mRemoteView.setTextViewText(R.id.txt_notifyMusicName, title);
			}
			if (!TextUtils.isEmpty(msg))
			{
				mRemoteView.setTextViewText(R.id.txt_notifyNickName, msg);
			}
			if (isPlaying)
			{
				mRemoteView.setImageViewResource(R.id.img_notifyPlayOrPause,
						R.drawable.notify_pause_xml);
			}
			else
			{
				mRemoteView.setImageViewResource(R.id.img_notifyPlayOrPause,
						R.drawable.notify_play_xml);
			}
			mNotificationManager.notify(mNotificationId, mNotification);
		}

		private void updateRemoteViewIcon(String coverUrl)
		{
			mFinalHttp.download(coverUrl, generateFilePath(null, coverUrl),
					new AjaxCallBack<File>()
					{

						@Override
						public void onSuccess(File t)
						{
							Log.e(TAG,
									"download bitmap success : "
											+ t.getAbsolutePath());
							if (t == null || !t.exists())
							{
								return;
							}
							Bitmap bt = BitmapFactory.decodeFile(t
									.getAbsolutePath());
							if (bt == null)
							{
								return;
							}
							mRemoteView.setImageViewBitmap(R.id.img_notifyIcon,
									bt);
							mNotificationManager.notify(mNotificationId,
									mNotification);
						}

						public void onFailure(Throwable t, int errorNo,
								String strMsg)
						{
							Log.e(TAG, "download bitmap error : " + errorNo
									+ ", " + strMsg + ", " + t.getMessage());
							mRemoteView
									.setImageViewResource(R.id.img_notifyIcon,
											R.drawable.ic_launcher);
							mNotificationManager.notify(mNotificationId,
									mNotification);
						}
					});
		}
		
		private void updateButtonStatus()
		{
			if (mPlayerManager.hasPreSound())
			{
				mBtnPreSound.setEnabled(true);
			}
			else
			{
				mBtnPreSound.setEnabled(false);
			}
			if (mPlayerManager.hasNextSound())
			{
				mBtnNextSound.setEnabled(true);
			}
			else
			{
				mBtnNextSound.setEnabled(false);
			}
		}

		@Override
		public void onPlayStop()
		{
			Log.e(TAG, "onPlayStop");
			mBtnPlay.setImageResource(R.drawable.widget_play_normal);
			updateNotification(null, null, false, true);
		}

		@Override
		public void onPlayStart()
		{
			Log.e(TAG, "onPlayStart");
			mBtnPlay.setImageResource(R.drawable.widget_pause_normal);
			updateNotification(null, null, true, true);
		}

		@Override
		public void onPlayProgress(int currPos, int duration)
		{
			String title = "";
			PlayableModel info = mPlayerManager.getCurrSound();
			if (info != null)
			{
				if (info instanceof Track)
				{
					title = ((Track) info).getTrackTitle();
				}
				else if (info instanceof Schedule)
				{
					title = ((Schedule) info).getRelatedProgram().getProgramName();
				}
				else if (info instanceof Radio)
				{
					title = ((Radio) info).getRadioName();
				}
			}
			mTextView.setText(title + "[" + ToolUtil.formatTime(currPos) + "/"
					+ ToolUtil.formatTime(duration) + "]");
			if (mUpdateProgress && duration != 0)
			{
				mSeekBar.setProgress((int) (100 * currPos / (float) duration));
			}
		}

		@Override
		public void onPlayPause()
		{
			Log.e(TAG, "onPlayPause");
			mBtnPlay.setImageResource(R.drawable.widget_play_normal);
		}

		@Override
		public void onSoundPlayComplete()
		{
			Log.e(TAG, "onSoundPlayComplete");
			mBtnPlay.setImageResource(R.drawable.widget_play_normal);
		}

		@Override
		public boolean onError(XmPlayerException exception)
		{
			Log.e(TAG, "onError");
			mBtnPlay.setImageResource(R.drawable.widget_play_normal);
			return false;
		}

		@Override
		public void onBufferProgress(int position)
		{
			mSeekBar.setSecondaryProgress(position);
		}

		public void onBufferingStart()
		{
			mSeekBar.setEnabled(false);
			mProgress.setVisibility(View.VISIBLE);
		}

		public void onBufferingStop()
		{
			mSeekBar.setEnabled(true);
			mProgress.setVisibility(View.GONE);
		}

	};

	private IXmAdsStatusListener mAdsListener = new IXmAdsStatusListener()
	{
		
		@Override
		public void onStartPlayAds(Advertis ad, int position)
		{
			Log.e(TAG, "onStartPlayAds, Ad:" + ad.getName() + ", pos:" + position);
			if (ad != null)
			{
				mFinalBitmap.display(mSoundCover, ad.getImageUrl());
			}
		}
		
		@Override
		public void onStartGetAdsInfo()
		{
			Log.e(TAG, "onStartGetAdsInfo");
			mBtnPlay.setEnabled(false);
			mSeekBar.setEnabled(false);
		}
		
		@Override
		public void onGetAdsInfo(AdvertisList ads)
		{
			Log.e(TAG, "onGetAdsInfo " + (ads != null));
		}
		
		@Override
		public void onError(int what, int extra)
		{
			Log.e(TAG, "onError what:" + what + ", extra:" + extra);
		}
		
		@Override
		public void onCompletePlayAds()
		{
			Log.e(TAG, "onCompletePlayAds");
			mBtnPlay.setEnabled(true);
			mSeekBar.setEnabled(true);
			PlayableModel model = mPlayerManager.getCurrSound();
			if (model != null && model instanceof Track)
			{
				mFinalBitmap.display(mSoundCover, ((Track) model).getCoverUrlLarge());
			}
		}
		
		@Override
		public void onAdsStopBuffering()
		{
			Log.e(TAG, "onAdsStopBuffering");
		}
		
		@Override
		public void onAdsStartBuffering()
		{
			Log.e(TAG, "onAdsStartBuffering");
		}
	}; 
}
